<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://lib.baomitu.com/socket.io/4.0.1/socket.io.js"></script>
    <style>
        *{
            margin: 0;
            padding: 0;
            list-style: none;
            box-sizing: border-box;
        }
        .container{
            width: 750px;
            height: 450px;
            border: 4px dashed #000;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            margin: 100px auto;
        }
        .header{
            display: flex;
            justify-content: space-around;
            height: 45px;
            line-height: 45px;
            text-align: center;
            box-shadow: 0px -30px 32px 10px #000;
        }
        .main{
            flex: 1;
            overflow-y: auto;
        }
        .send-msg{
            height: 50px;
            display: flex;
        }
        .send-msg button{
            height: 35px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <p>用户id: <b id="uid"></b></p><p>在线人数:<b id="allPeople">0</b></p>
        </div>
        <div class="main" id="main">
            
        </div>
        <div class="send-msg">
            <p>内容<input type="text" name="" id="msg"/></p>
            <button id="btn">发送</button>
        </div>
    </div>
    <script>
        var socket = io.connect('10.1.37.25:80');
        var msgList = [];
        let currentAlive = 0;
        let uuid='';
        //连接成功消息
        socket.on('open', function (data) {
            console.log(data);
            uuid= data.uuid;
            allPeople.innerHTML = data.currentAlive
            uid.innerHTML=uuid;
        });
        //更新总人数
        socket.on('currentAlive', function (data) {
            const {currentAlive } = data;
            allPeople.innerHTML=currentAlive;
        })
        //发送消息
        btn.onclick=()=>{
            console.log('发送消息');
            socket.emit('chat',{ 
                msg:msg.value,
            });
        }

        //聊天信息
        socket.on('chat',function(data){
            console.log('chat',data);
        })

        //接受聊天消息
        socket.on('getMessage', function (data) {
            const {id,msg } = data;
            Object.assign(data,{date:new Date().toLocaleDateString(),time:new Date().toLocaleTimeString()})
            msgList.push(data)
            main.innerHTML=msgList.map(item=>{
                return`<div class="main-item">
                    <div class="main-item-head">
                        <b>${item.id}</b><span>${item.date} ${item.time}</span>
                    </div>
                    <div class="main-item-msg">${item.msg}</div>
                </div>`
            }).join('')
        })
      </script>
</body>
</html>